/**
 * 神秘时代4计算器
 * @authors 619608182@qq.com
 * @date    2015-04-29 12:52:53
 * @version 1
 */
$(function() {

    'use strict';

    var one = null,
        two = null,
        oneImage = $('#oneImg'),
        twoImage = $('#twoImg'),
        oneText = $('#oneText'),
        twoText = $('#twoText');


    //获取是否启用了禁忌魔法的cookie
    var enableForbiddenCookie = $.cookie("enableForbiddenCookie");
    if(enableForbiddenCookie == "true")
    {
        $("#enableForbidden").attr("checked",true);
        aspects = aspects.concat(forbidden);
    }

    //元素列表
    var html = "";
    for (var i = 0, l = aspects.length; i < l; i++) {
        html += '<div id="' + aspects[i].enname + '" class="block"><img src="images/aspects/' + aspects[i].mod + '/' + aspects[i].enname + '.png" ><div class="title">' + aspects[i].cnname + '</div></div>';
    }
    $(".aspects").html(html);

    //禁忌魔法选择事件
    $("#enableForbidden").on("click",function(){
        $.cookie("enableForbiddenCookie",$(this).prop("checked"));
        location.href = location;
    });

    //绑定点击事件
    $(".block").on("click", function() {
        var $this = $(this);
        var id = this.id;
        if ($this.hasClass('selected')) {
            //如果取消了第一个,就把第二个向前移动一下
            if (one === id) {
                one = two;
                two = null;
            } else {
                two = null;
            }
        } else {
            //如果一个没有就给第一个赋值
            if (one == null) {
                one = id;
            } else {
                //如果第二个也有值,就先删除
                if (two != null) {
                    $("#" + two).removeClass('selected');
                }
                two = id;
            }
        }
        $this.toggleClass('selected');

        //这里设置下面的已选择元素
        showSelect();
    });


    //左右两个选择的元素交换
    $('#change').on('click', function() {
        //确保已经选择了两个
        if (one == null || two == null) return;
        //交换元素
        var temp = one;
        one = two;
        two = temp;
        showSelect();
    });


    //计算按钮
    $('#calc').on('click', function() {
        var stepNumber = parseInt($('#stepNumber').val());
        if (isNaN(stepNumber)) {
            alert('元素数量必须为数字!');
            return;
        } else if (stepNumber <= 0) {
            alert('元素数量不可以少于1!');
            return;
        } else if (stepNumber > 8) {
            alert('元素数量不可以大于8!');
            return;
        } else if (one == null || two == null) {
            alert('必须两个元素进行计算');
            return;
        }
        var oneApts = getEleByEname(one);
        var twoApts = getEleByEname(two);
        var result = calc(oneApts, twoApts, stepNumber);

        //计算基础元素数量
        for(var i = 0,l=result.length ;i<l;i++)
        {
            var subs = {};
            for(var j = 1;j<result[i].length-1;j++)
            {
                getBasicElement(subs,result[i][j]);
            }
            result[i].subs = subs;
            //计算总数
            var sum = 0;
            for(var k in subs){
                sum += subs[k];
            }
            result[i].subs.sum = sum;
        }

        //按照元素多少排序
        result.sort(function(a,b){
            return a.subs.sum - b.subs.sum;
        });

        //添加到页面
        var html = "";
        for (var i = 0; i < result.length; i++) {
            var obj = {};
            var r = result[i];
            //序号
            html += '<div class="r"><div class="num">' + (i + 1) + '.</div>';

            for (var j = 0; j < r.length; j++) {
                html += '<div id="' + r[j].enname + '" class="block"><img src="images/aspects/' + r[j].mod + '/' + r[j].enname + '.png" ><div class="title">' + r[j].cnname + '</div></div>';
            }
            html += '</div>';

            html += '<div class="total">基础元素<span>'+ r.subs.sum +'</span>个：';
            for(var k in r.subs){
                //把总数去掉
                if(k === "sum") continue;
                html += k+' <span>'+ r.subs[k] +'</span> 个 &nbsp;';
            }
            html += '</div>';
        }

        $(".result").html(html);

        $("#r1").html(oneApts.cnname);
        $("#r2").html(twoApts.cnname);
        $("#r").html(result.length);

    });


    function getBasicElement(obj,ele){
        if(ele.subs.length<=0){
            if(ele.cnname in obj){
                obj[ele.cnname]++;
            }else{
                obj[ele.cnname] = 1;
            }
        }else{
            getBasicElement(obj,getEleByEname(ele.subs[0]));
            getBasicElement(obj,getEleByEname(ele.subs[1]));
        }
    }

    $('.block').each(function() { // Notice the .each() loop, discussed below
        var html = "";
        var id = this.id;
        var aspt = getEleByEname(id);
        if (aspt.subs.length <= 0) {
            return;
        }

        var sub1 = getEleByEname(aspt.subs[0]),
            sub2 = getEleByEname(aspt.subs[1]);
        html = '<div class="xtip">' +
            '<img src="images/aspects/' + sub1.mod + '/' + sub1.enname + '.png" />' +
            '<div class="name">' + sub1.cnname + '</div>' +
            '<div class="m">+</div>' +
            '<img src="images/aspects/' + sub2.mod + '/' + sub2.enname + '.png" />' +
            '<div class="name">' + sub2.cnname + '</div>' +
            '</div>';
        $(this).qtip({
            content: {
                text: html
            },
            position:{
                my:'top center',
                at: 'bottom center'
            },
            style: {
                classes: 'qtip-blue qtip-shadow'
            }
        });
    });

    //计算
    function calc(o, t, step) {
        var result = [
            [o]
        ];

        while ((step--) >= 0) {
            //临时的结果
            var tempResult = [];
            //循环上一次连接的所有结果,并找到可以连接最后一个的
            for (var i = 0; i < result.length; i++) {
                //缓存循环项
                var resultOne = result[i];
                //当前结果中的最后一个元素
                var aptsLast = resultOne[resultOne.length - 1];


                //遍历所有元素,找到能合成的
                for (var j = 0, jl = aspects.length; j < jl; j++) {
                    var apts = aspects[j];
                    //sub中是否包含元素
                    if (aptsLast.subs.length > 0 && (aptsLast.subs[0] === apts.enname || aptsLast.subs[1] === apts.enname)) {
                        var temp = resultOne.slice(0);
                        temp.push(apts);
                        tempResult.push(temp);
                    } else if (apts.subs.length > 0 && (apts.subs[0] === aptsLast.enname || apts.subs[1] === aptsLast.enname)) {
                        var temp = resultOne.slice(0);
                        temp.push(apts);
                        tempResult.push(temp);
                    }
                }
            }
            result = tempResult;
        }

        //遍历结果,筛选出最后一个元素符合需求的
        var rtn = [];
        for (var i = 0; i < result.length; i++) {
            if (result[i][result[i].length - 1].enname === t.enname) {
                rtn.push(result[i]);
            }
        }

        return rtn;
    }


    //把选择的元素显示在界面上
    function showSelect() {
        if (one != null) {
            var apts = getEleByEname(one);
            oneImage.attr('src', 'images/aspects/' + apts.mod + '/' + apts.enname + '.png');
            oneText.html(apts.cnname);
        } else {
            oneImage.attr('src', 'images/no.png');
            oneText.html("未选择");
        }
        if (two != null) {
            var apts = getEleByEname(two);
            twoImage.attr('src', 'images/aspects/' + apts.mod + '/' + apts.enname + '.png');
            twoText.html(apts.cnname);
        } else {
            twoImage.attr('src', 'images/no.png');
            twoText.html("未选择");
        }
    }

    //根据ename获取元素
    function getEleByEname(ename) {
        for (var i = 0; i < aspects.length; i++) {
            if (aspects[i].enname === ename) {
                return aspects[i];
            }
        }
        return null;
    }
});